package cn.laixueit.cart.controller;

import cn.laixueit.cart.pojo.item.Category;
import cn.laixueit.cart.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /*@GetMapping("/list")
    public ResponseEntity<List<Category>> list(){
        List<Category> categories = categoryService.list();
        return ResponseEntity.ok(categories);
    }*/

    @GetMapping("/list")
    public ResponseEntity<Collection<Category>> list(Long pid){
        HashMap<String, Object> map = new HashMap<>();
        map.put("parent_id",pid);
        Collection<Category> categories = categoryService.listByMap(map);
        return ResponseEntity.ok(categories);
    }

    @PostMapping("/save")
    public ResponseEntity<Void> save(@RequestBody Category category){
        try {
            categoryService.save(category);
        }catch (Exception e){
            return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    @GetMapping("/{id}")
    public ResponseEntity<Category> getCategoryById(@PathVariable("id") Long id){
        return ResponseEntity.ok(categoryService.getById(id));
    }


    @GetMapping("/names")
    public ResponseEntity<List<String>> names(@RequestParam("ids")List<Long> ids){
        List<String> names = categoryService.categoryNames(ids);
        return  ResponseEntity.ok(names);
    }
}
